import { getAuthMenuApi } from '@/apis/auth'
import type { getAuthApi, Children } from '@/types/auth'
import { defineStore } from 'pinia'
import { ref } from 'vue'
import router from '@/router/index'

function view(path: string) {
  // 首先把你需要动态路由的组件地址全部获取
  const modules = import.meta.glob('../**/*.vue')
  // 然后动态路由的时候这样来取
  return modules['../views/' + path.replace('@/views/', '')]
}

export const userAsideStore = defineStore('aside', () => {
  //声明数据 相对于State
  const isCollspace = ref(false)

  // 菜单
  const menu = ref([] as getAuthApi[])
  // 获取菜单
  const getMenu = async () => {
    const res = await getAuthMenuApi()
    menu.value = res.data.data
    // console.log(res)

    // 动态路由
    res.data.data.forEach((oneMenu: getAuthApi, oneI: number) => {
      if (oneMenu.children && oneMenu.children.length > 0) {
        oneMenu.children.forEach((twoMenu: Children, twoI: number) => {
          // console.log(111, twoMenu.path, `@/views/${twoMenu.component}.vue`)
          // 给name叫admin的路由，动态添加子路由
          router.addRoute('layout', {
            name: `adminSon${oneI}${twoI}`, // 给所有子路由添加名字，后期删除（唯一）
            path: twoMenu.path,
            // component: () => import(`${twoMenu.component}`),
            component: view(twoMenu.component),
            meta: {
              name1: twoMenu.auth_pname,
              name2: twoMenu.auth_name,
              keep_alive: twoMenu.keep_alive,
            },
          })
          // ....
        })
      }
    })
  }
  // 清空菜单
  const clearMenu = () => {
    // 清空路由uthInfo
    menu.value.forEach((oneMenu: getAuthApi, oneI: number) => {
      if (oneMenu.children && oneMenu.children.length > 0) {
        oneMenu.children.forEach((twoMen: Children, twoI: number) => {
          router.removeRoute(`adminSon${oneI}${twoI}`)
        })
      }
    })
    // 清空菜单
    menu.value = []
  }

  return {
    isCollspace,
    menu,
    getMenu,
    clearMenu,
  }
})
